﻿using System;
using System.Runtime.InteropServices;
using boda.net.wpf.core.Helper;

namespace boda.net.wpf.core.Models;

/// <summary>
/// 非托管数组基类
/// </summary>
public abstract class UnmanagedArrayBase : IDisposable
{
    /// <summary>
    /// 图像数据的指针
    /// </summary>
    public IntPtr Header { get; private set; }

    /// <summary>
    /// 元素的数量
    /// </summary>
    public long Count { get; }

    /// <summary>
    /// 单个元素的字节数长度
    /// </summary>
    public readonly int Size;


    public long Length => Size * Count;

    protected UnmanagedArrayBase(long count, int size, bool isResetMemory = true)
    {
        if (count <= 0) throw new ArgumentException("count 不能小于零");
        if (size <= 0) throw new ArgumentException("size 不能小于零");
        Count = count;
        Size = size;

        Header = Marshal.AllocHGlobal(new IntPtr(Length));
        if (isResetMemory)
        {
            MemoryHelper.ZeroMemory(Header, Length);
        }
    }

    ~UnmanagedArrayBase()
    {
        Dispose();
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected bool disposed;

    protected void Dispose(bool disposing)
    {
        if (disposed) return;
        if(disposing)
        {
            // TODO 清理托管的内容
        }
        if (Header != IntPtr.Zero)
        {
            Marshal.FreeHGlobal(Header);
        }
        disposed = true;
    }
}
